<template>
  <a-modal
    :title="editBoxState ? '编辑banner' : '新增banner'"
    :visible.sync="visible"
    @ok="handleSubmit"
    @cancel="handleCancel(false)"
  >
    <a-form :form="form">
      <a-form-item
        label="标题"
        :label-col="{ span: 5 }"
        :wrapper-col="{ span: 19 }"
      >
        <a-input
          v-decorator="[
            'title',
            {
              initialValue: initInfo.title,
              rules: [
                { required: true, message: '请输入标题！' },
                {
                  validator: $validate.validateLength,
                  max: 20,
                  min: 1
                }
              ]
            }
          ]"
        />
      </a-form-item>
      <a-form-item
        label="跳转链接"
        :label-col="{ span: 5 }"
        :wrapper-col="{ span: 19 }"
      >
        <a-input
          v-decorator="[
            'url',
            {
              initialValue: initInfo.url,
              rules: [{ required: true, message: '请输入您需要跳转的链接' }]
            }
          ]"
        >
        </a-input>
      </a-form-item>
      <a-form-item
        label="选择图片"
        :label-col="{ span: 5 }"
        :wrapper-col="{ span: 19 }"
        help="建议图片宽高为：1920px*797px"
      >
        <a-upload
          v-decorator="[
            'upload',
            {
              initialValue: initInfo.upload,
              valuePropName: 'fileList',
              getValueFromEvent: normFile,
              rules: [{ required: true, message: '请选择图片' }]
            }
          ]"
          accept="image/*"
          name="file"
          :multiple="false"
          :action="$api.upload"
          :data="postData"
          :beforeUpload="beforeUpload"
        >
          <a-button> <a-icon type="upload" /> 上传图片 </a-button>
        </a-upload>
      </a-form-item>
      <a-form-item
        label="状态"
        :label-col="{ span: 5 }"
        :wrapper-col="{ span: 19 }"
      >
        <a-select
          v-decorator="[
            'status',
            {
              initialValue: initInfo.status,
              rules: [{ required: true, message: '必选项' }]
            }
          ]"
        >
          <a-select-option value="1">
            启用
          </a-select-option>
          <a-select-option value="2">
            停用
          </a-select-option>
        </a-select>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script>
import { getToken } from "@/tool/qiniu";
export default {
  name: "add",
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    editBoxState: {
      type: Number, //编辑弹出框状态，0为新增框，1为编辑框
      default: 0
    },
    editInfo: {
      type: Object
    }
  },
  data() {
    this.handleSubmit = this.$debounce(this.handleSubmit, 800);
    return {
      formLayout: "horizontal",
      form: this.$form.createForm(this),
      postData: {
        token: ""
      },
      initInfo: {}
    };
  },
  methods: {
    handleSubmit(e) {
      e.preventDefault();
      this.form.validateFields((err, values) => {
        if (!err) {
          let obj = JSON.parse(JSON.stringify(values));
          if (values.upload) {
            obj.pic = values.upload[0].response.key;
          }
          let api = null;
          if (this.editBoxState === 0) {
            obj.type = 1;
            api = this.$api.addBannerList;
          } else {
            obj.id = this.initInfo.id;
            obj.type = 2;
            api = this.$api.editBannerList;
          }
          delete obj.upload;
          this.$ajax
            .post(api, obj)
            .then(() => {
              this.$notification.success({
                message: "操作成功"
              });
              this.handleCancel(true);
            })
            .catch(err => {
              this.$notification.error({
                message: err
              });
            });
        }
      });
    },
    handleCancel(isFresh) {
      this.form.resetFields();
      this.$emit("handleCancel", isFresh);
    },
    beforeUpload(file) {
      let timestamp2 = new Date().getTime();
      let typeArr = file.name.split(".");
      let type = typeArr[typeArr.length - 1];
      let savekey = "cxxy/banner/" + timestamp2 + "." + type;
      this.postData.token = getToken(savekey);
      let _this = this;
      let imgWidth = "";
      let imgHight = "";
      const isSize = new Promise(function(resolve, reject) {
        let width = 1920;
        let height = 797;
        let _URL = window.URL || window.webkitURL;
        let img = new Image();
        img.onload = function() {
          imgWidth = img.width;
          imgHight = img.height;
          let valid = img.width == width && img.height == height;
          valid ? resolve() : reject();
        };
        img.src = _URL.createObjectURL(file);
      }).then(
        () => {
          return file;
        },
        () => {
          _this.$notification.error({
            message:
              "图片大小不符合标准,宽高为1920px*797px。当前上传图片的宽高分别为：" +
              imgWidth +
              "px和" +
              imgHight +
              "px"
          });
          return Promise.reject();
        }
      );
      return isSize;
    },
    normFile(e) {
      if (e.fileList.length > 1) {
        e.fileList.splice(0, 1);
      }
      return e && e.fileList;
    }
  },
  watch: {
    editInfo: {
      handler: function(val) {
        this.initInfo = JSON.parse(JSON.stringify(val));
      },
      deep: true
    }
  }
};
</script>

<style scoped></style>
